package com.xzq.busgstack.client;

import com.xzq.busgstack.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/**
 * @Author xzq
 * @Description //TODO
 * @Date 2021/11/20 14:49
 * @Version 1.0.0
 **/
public class MyClientHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("消息类型：" + msg.getClass());
        System.out.println("消息内容："+msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel sc = (SocketChannel) ctx.channel();
        System.out.println("连接建立...");
        System.out.println("服务端IP：" + sc.localAddress().getHostString());
        System.out.println("服务端端口：" + sc.localAddress().getPort());

        //通知服务端连接建立成功
        String str = "我是客户端,已经成功连接上了你";
        ctx.writeAndFlush(MsgUtil.buildMsg(sc.id().toString(), str));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与服务端断开连接....");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("连接异常： \r\n" + cause.getMessage());
    }
}
